import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { DragDropContext } from 'react-beautiful-dnd';
import { 
  Typography, 
  Alert, 
  Input, 
  Select, 
  Button, 
  Space, 
  Row, 
  Col, 
  Form,
  message,
  Modal,
  Spin,
  Tag,
  Card
} from 'antd';
import { 
  CheckCircleOutlined, 
  SyncOutlined, 
  ClockCircleOutlined, 
  InfoCircleOutlined,
  SearchOutlined,
  UserOutlined,
  PlusOutlined,
  CloseCircleOutlined,
  ReloadOutlined,
  AppstoreOutlined
} from '@ant-design/icons';
import { 
  TaskColumn as TaskColumnType, 
  TaskStatus, 
  Task, 
  TaskQueryParams,
  TaskType,
  TaskSubType,
  TaskLevel,
  getSubTypesByType,
  taskTypes
} from './models/taskModels';
import TaskColumn from './components/TaskColumn';
import { searchTasks, getMyTasks, updateTaskStatus, createTask, updateTask } from '../../services/taskService';
import { getStoredUserInfo } from '../../utils/auth';
import { getUserNames } from '../../services/user';
import TaskDetailModal from './components/TaskDetailModal';
import dayjs from 'dayjs';
import CreateTaskModal from './components/CreateTaskModal';
import TaskEditModal from './components/TaskEditModal';

const { Title, Paragraph } = Typography;
const { Option } = Select;
const { Search } = Input;

// 定义 DropResult 类型
interface DropResult {
  draggableId: string;
  type: string;
  source: {
    droppableId: string;
    index: number;
  };
  destination?: {
    droppableId: string;
    index: number;
  };
}

/**
 * 任务看板页面
 * 展示待处理、进行中和已完成的任务，支持任务拖拽功能
 */
const TaskBoard: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [newTaskModalVisible, setNewTaskModalVisible] = useState(false);
  const [createTaskForm] = Form.useForm();
  const [selectedType, setSelectedType] = useState<TaskType>('业务需求');
  const [username, setUsername] = useState<string>(''); // 用户英文名
  const [userOptions, setUserOptions] = useState<{ label: string; value: string }[]>([]);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [draggedTask, setDraggedTask] = useState<Task | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [taskDetailVisible, setTaskDetailVisible] = useState(false);
  const [createTaskVisible, setCreateTaskVisible] = useState(false);
  const [taskEditVisible, setTaskEditVisible] = useState(false);
  const [isInProgressEdit, setIsInProgressEdit] = useState(false); // 新增：标记是否是进行中列的编辑

  // 初始化列数据
  const initialColumns: TaskColumnType[] = [
    {
      id: 'todo',
      title: '待处理',
      icon: <ClockCircleOutlined style={{ color: '#1890ff' }} />, // 使用蓝色,与待处理状态匹配
      tasks: [],
    },
    {
      id: 'inProgress',
      title: '进行中',
      icon: <SyncOutlined  style={{ color: '#faad14' }}/>,  // 使用黄色,与进行中状态匹配
      tasks: [],
    },
    {
      id: 'done',
      title: '已完成',
      icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,  // 使用绿色,与已完成状态匹配
      tasks: [],
    },
  ];

  // 状态管理
  const [columns, setColumns] = useState<TaskColumnType[]>(initialColumns);

  // 获取当前用户信息
  useEffect(() => {
    const userInfo = getStoredUserInfo();
    if (userInfo && userInfo.englishName) {
      setUsername(userInfo.englishName);
    } else {
      message.error('获取用户信息失败');
    }
  }, []);

  // 获取任务列表
  const fetchTasks = async (params?: TaskQueryParams) => {
    try {
      setLoading(true);
      const response = await searchTasks(params || {});
      
      if (response.code === 200 && response.data) {
        const newColumns = [...initialColumns];
        
        // 填充任务数据
        Object.entries(response.data).forEach(([status, tasks]) => {
          const columnIndex = newColumns.findIndex(col => col.id === status);
          if (columnIndex >= 0) {
            newColumns[columnIndex].tasks = tasks as Task[];
          }
        });
        
        setColumns(newColumns);
      } else {
        message.error('获取任务列表失败');
      }
    } catch (error) {
      console.error('获取任务列表失败:', error);
      message.error('获取任务列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取我的任务
  const fetchMyTasks = async () => {
    if (!username) {
      message.error('用户信息不完整，无法获取任务');
      return;
    }

    try {
      setLoading(true);
      // 传递英文名，确保后端能够识别用户
      const response = await getMyTasks(username);
      
      if (response.code === 200 && response.data) {
        const newColumns = [...initialColumns];
        
        // 填充任务数据
        Object.entries(response.data).forEach(([status, tasks]) => {
          const columnIndex = newColumns.findIndex(col => col.id === status);
          if (columnIndex >= 0) {
            newColumns[columnIndex].tasks = tasks as Task[];
          }
        });
        
        setColumns(newColumns);
      } else {
        message.error('获取我的任务失败');
      }
    } catch (error) {
      console.error('获取我的任务失败:', error);
      message.error('获取我的任务失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载
  useEffect(() => {
    if (username) {
      fetchTasks();
    }
  }, [username]);

  // 处理搜索
  const handleSearch = () => {
    const values = form.getFieldsValue();
    
    // 处理subTypes字段，如果是数组则转换为竖线分隔的字符串
    const formattedValues = { ...values };
    if (formattedValues.subTypes && Array.isArray(formattedValues.subTypes)) {
      formattedValues.subTypes = formattedValues.subTypes.join(',');
    }
    
    fetchTasks({
      ...formattedValues,
      currentUser: username, // 使用英文名作为currentUser
    });
  };

  // 处理拖拽结束
  const handleDragEnd = async (result: DropResult) => {
    const { destination, source, draggableId } = result;

    // 如果没有目标位置，不做任何处理
    if (!destination) {
      return;
    }
    
    // 如果拖到了原来的位置，不做任何处理
    if (destination.droppableId === source.droppableId && 
        destination.index === source.index) {
      return;
    }
    
    // 找到拖拽的任务
    const sourceColumn = columns.find(col => col.id === source.droppableId);
    const destinationColumn = columns.find(col => col.id === destination.droppableId);
    
    if (!sourceColumn || !destinationColumn) return;

    // 获取要移动的任务
    const taskToMove = sourceColumn.tasks[source.index];
    
    // 如果是在同一列内拖动（排序），只需要更新前端状态
    if (source.droppableId === destination.droppableId) {
      console.log('【拖拽排序】在同一列内进行任务排序:', source.index, '->', destination.index);
      
      // 创建新的任务数组（复制原数组）
      const newTasks = [...sourceColumn.tasks];
      // 从原位置删除任务
      newTasks.splice(source.index, 1);
      // 插入到新位置
      newTasks.splice(destination.index, 0, taskToMove);
      
      // 更新列数据
      const columnIndex = columns.findIndex(col => col.id === source.droppableId);
      const newColumns = [...columns];
      newColumns[columnIndex] = {
        ...sourceColumn,
        tasks: newTasks
      };
      
      // 更新状态
      setColumns(newColumns);
      return;
    }
    
    // 需求2：从"待处理"拖到"已完成"，禁止操作
    if (source.droppableId === 'todo' && destination.droppableId === 'done') {
      message.error('不允许将待处理任务直接拖拽到已完成状态');
      return;
    }
    
    // 需求5：从"已完成"拖到"待处理"，禁止操作
    if (source.droppableId === 'done' && destination.droppableId === 'todo') {
      message.error('不允许将已完成任务直接拖拽到待处理状态');
      return;
    }
    
    // 需求1：如果是从"待处理"拖到"进行中"，显示编辑弹窗
    if (source.droppableId === 'todo' && destination.droppableId === 'inProgress') {
      // 过滤掉"暂无"开头的默认值，但保留类型安全
      const filteredTask: Task = {
        ...taskToMove,
        // 如果是以"暂无"开头的，替换为空字符串以便用户必须选择有效值
        type: taskToMove.type?.startsWith('暂无') ? '' as TaskType : taskToMove.type,
        subType: taskToMove.subType?.startsWith('暂无') ? '' as TaskSubType : taskToMove.subType,
        level: taskToMove.level?.startsWith('暂无') ? '' as TaskLevel : taskToMove.level,
        status: 'inProgress' as TaskStatus, // 需求1：确保状态为inProgress
        finishedDate: undefined, // 需求1：设置finishedDate为空
        // 确保处理进度至少为1%
        process: taskToMove.process && taskToMove.process > 0 ? taskToMove.process : 1,
        // 确保保留parentId
        parentId: taskToMove.parentId
      };
      
      setDraggedTask(filteredTask);
      setEditModalVisible(true);
      return; // 暂不执行后续逻辑，等待用户编辑
    }
    
    // 需求3：从"进行中"拖到"已完成"
    if (source.droppableId === 'inProgress' && destination.droppableId === 'done') {
      try {
        const currentDate = dayjs().format('YYYY-MM-DD');
        const updatedTask: Partial<Task> = {
          id: taskToMove.id,
          status: 'done' as TaskStatus,
          finishedDate: currentDate,
          process: 100,
          updater: username,
          // 添加其他默认字段
          title: taskToMove.title,
          type: taskToMove.type,
          subType: taskToMove.subType,
          level: taskToMove.level,
          receiver: taskToMove.receiver,
          thisWeekPlan: taskToMove.thisWeekPlan,
          nextWeekPlan: taskToMove.nextWeekPlan,
          problems: taskToMove.problems,
          creater: taskToMove.creater,
          expectedDate: taskToMove.expectedDate,
          // 保留父任务ID
          parentId: taskToMove.parentId
        };
        
        const response = await updateTask(taskToMove.id, updatedTask);
        
        if (response.code === 200) {
          // 更新列数据
          const sourceColumnIndex = columns.findIndex(col => col.id === source.droppableId);
          const destColumnIndex = columns.findIndex(col => col.id === destination.droppableId);
          
          // 从源列中移除任务
          const newColumns = [...columns];
          newColumns[sourceColumnIndex] = {
            ...sourceColumn,
            tasks: sourceColumn.tasks.filter((_, index) => index !== source.index)
          };
          
          // 在目标列中添加更新后的任务
          const updatedTaskFull = {
            ...taskToMove,
            ...updatedTask
          };
          
          const newDestTasks = [...destinationColumn.tasks];
          newDestTasks.splice(destination.index, 0, updatedTaskFull as Task);
          
          newColumns[destColumnIndex] = {
            ...destinationColumn,
            tasks: newDestTasks
          };
          
          // 更新状态
          setColumns(newColumns);
          message.success('任务已完成！');
        } else {
          message.error('任务状态更新失败');
        }
      } catch (error) {
        console.error('更新任务状态失败:', error);
        message.error('更新任务状态失败');
      }
      return;
    }
    
    // 需求4：从"已完成"拖到"进行中"
    if (source.droppableId === 'done' && destination.droppableId === 'inProgress') {
      try {
        const updatedTask: Partial<Task> = {
          id: taskToMove.id,
          status: 'inProgress' as TaskStatus,
          finishedDate: undefined, // 设置为空
          process: 50, // 设置为50%
          updater: username,
          // 保留原有的基本信息
          title: taskToMove.title,
          titleIndex: taskToMove.titleIndex,
          creater: taskToMove.creater,
          createdTime: taskToMove.createdTime,
          // 保留任务分类信息
          type: taskToMove.type,
          subType: taskToMove.subType,
          level: taskToMove.level,
          // 保留任务计划信息
          thisWeekPlan: taskToMove.thisWeekPlan,
          nextWeekPlan: taskToMove.nextWeekPlan,
          problems: taskToMove.problems,
          expectedDate: taskToMove.expectedDate,
          // 保留任务负责人和父任务ID
          receiver: taskToMove.receiver,
          parentId: taskToMove.parentId
        };
        
        const response = await updateTask(taskToMove.id, updatedTask);
        
        if (response.code === 200) {
          // 更新列数据
          const sourceColumnIndex = columns.findIndex(col => col.id === source.droppableId);
          const destColumnIndex = columns.findIndex(col => col.id === destination.droppableId);
          
          // 从源列中移除任务
          const newColumns = [...columns];
          newColumns[sourceColumnIndex] = {
            ...sourceColumn,
            tasks: sourceColumn.tasks.filter((_, index) => index !== source.index)
          };
          
          // 在目标列中添加更新后的任务
          const updatedTaskFull = {
            ...taskToMove,
            ...updatedTask
          };
          
          const newDestTasks = [...destinationColumn.tasks];
          newDestTasks.splice(destination.index, 0, updatedTaskFull as Task);
          
          newColumns[destColumnIndex] = {
            ...destinationColumn,
            tasks: newDestTasks
          };
          
          // 更新状态
          setColumns(newColumns);
          message.success('任务状态已更新为进行中');
        } else {
          message.error('任务状态更新失败');
        }
      } catch (error) {
        console.error('更新任务状态失败:', error);
        message.error('更新任务状态失败');
      }
      return;
    }
    
    // 需求6：如果是从"进行中"拖到"待处理"，重置任务信息
    if (source.droppableId === 'inProgress' && destination.droppableId === 'todo') {
      try {
        // 创建一个只保留title, title_index, creater, created_time的新任务对象
        const resetTask: Partial<Task> = {
          id: taskToMove.id,
          title: taskToMove.title,
          titleIndex: taskToMove.titleIndex, // 保留title_index
          creater: taskToMove.creater,
          createdTime: taskToMove.createdTime, // 保留created_time
          status: 'todo' as TaskStatus,
          // 重置其他字段为null
          type: '暂无分类' as TaskType,
          subType: '暂无子分类' as TaskSubType,
          level: '暂无' as TaskLevel, 
          receiver: undefined,
          process: 0,
          thisWeekPlan: undefined,
          nextWeekPlan: undefined,
          problems: undefined,
          expectedDate: undefined,
          finishedDate: undefined,
          updater: username,
          // 保留父任务ID
          parentId: taskToMove.parentId
        };
        
        // 使用updateTask方法更新完整的任务数据
        const response = await updateTask(taskToMove.id, resetTask);
        
        if (response.code === 200) {
          // 更新列数据
          const sourceColumnIndex = columns.findIndex(col => col.id === source.droppableId);
          const destColumnIndex = columns.findIndex(col => col.id === destination.droppableId);
          
          // 从源列中移除任务
          const newColumns = [...columns];
          newColumns[sourceColumnIndex] = {
            ...sourceColumn,
            tasks: sourceColumn.tasks.filter((_, index) => index !== source.index)
          };
          
          // 在目标列中添加重置后的任务
          const newDestTasks = [...destinationColumn.tasks];
          newDestTasks.splice(destination.index, 0, resetTask as Task);
          
          newColumns[destColumnIndex] = {
            ...destinationColumn,
            tasks: newDestTasks
          };
          
          // 更新状态
          setColumns(newColumns);
          message.success('任务已重置并移至待处理列');
        } else {
          message.error('任务状态更新失败');
        }
      } catch (error) {
        console.error('更新任务状态失败:', error);
        message.error('更新任务状态失败');
      }
      return;
    }
    
    // 处理其他拖拽情况（保留原有的默认处理逻辑）
    try {
      // 设置拖拽到已完成列时的完成时间
      let additionalData = {};
      if (destination.droppableId === 'done') {
        additionalData = {
          finishedDate: dayjs().format('YYYY-MM-DD')
        };
      }
      
      // 调用API更新任务状态
      const response = await updateTaskStatus(taskToMove.id, destination.droppableId, username);
      
      if (response.code === 200) {
        // 更新任务状态
        const updatedTask = {
          ...taskToMove,
          status: destination.droppableId as TaskStatus,
          updateTime: new Date().toISOString(),
          updater: username,
          parentId: taskToMove.parentId, // 保留原有的父任务ID
          ...additionalData // 添加额外数据（如完成时间）
        };

        // 如果拖到done状态，还需要额外更新完成时间
        if (destination.droppableId === 'done') {
          // 更新完成时间
          await updateTask(taskToMove.id, {
            finishedDate: dayjs().format('YYYY-MM-DD')
          });
        }

        // 更新列数据
        const sourceColumnIndex = columns.findIndex(col => col.id === source.droppableId);
        const destColumnIndex = columns.findIndex(col => col.id === destination.droppableId);
        
        // 从源列中移除任务
        const newColumns = [...columns];
        newColumns[sourceColumnIndex] = {
          ...sourceColumn,
          tasks: sourceColumn.tasks.filter((_, index) => index !== source.index)
        };
        
        // 在目标列中添加任务
        const newDestTasks = [...destinationColumn.tasks];
        newDestTasks.splice(destination.index, 0, updatedTask);
        
        newColumns[destColumnIndex] = {
          ...destinationColumn,
          tasks: newDestTasks
        };
        
        // 更新状态
        setColumns(newColumns);
        message.success('任务状态更新成功');
      } else {
        message.error('任务状态更新失败');
      }
    } catch (error) {
      console.error('更新任务状态失败:', error);
      message.error('更新任务状态失败');
    }
  };

  // 取消编辑
  const handleEditCancel = () => {
    setEditModalVisible(false);
    setDraggedTask(null);
  };

  // 处理任务类型变更
  const handleTypeChange = (value: TaskType) => {
    setSelectedType(value);
    form.setFieldValue('subTypes', undefined);
  };

  // 获取用户名称列表
  const fetchUserNames = async () => {
    try {
      setLoadingUsers(true);
      const res = await getUserNames();
      if (res.code === 200 && res.data) {
        // 将后端返回的 "englishName/chineseName" 格式转换为下拉选项
        const options = res.data.map(item => {
          const [englishName, chineseName] = item.split('/');
          return {
            label: `${chineseName} (${englishName})`,
            value: item // 保存完整的 "englishName/chineseName" 字符串
          };
        });
        setUserOptions(options);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      setLoadingUsers(false);
    }
  };

  // 处理多选处理人
  const handleReceiversChange = (values: string[]) => {
    // 不需要在这里将列表转换为字符串，只保存列表值
    createTaskForm.setFieldValue('receiver', values);
  };

  // 处理新建任务
  const handleCreateTask = async () => {
    try {
      const values = await createTaskForm.validateFields();
      
      // 将处理人数组转换为格式化的字符串
      const formattedReceiver = values.receiver && values.receiver.length > 0 
        ? values.receiver.join('|') 
        : undefined;
      
      // 这里需要保持type、subType和level的默认值，即使表单中没有显示这些字段
      const taskData: Partial<Task> = {
        ...values,
        receiver: formattedReceiver, // 使用格式化后的处理人字符串
        status: 'todo',
        creater: username,
        type: '暂无分类',  // 设置默认值
        subType: '暂无子分类', // 设置默认值
        level: '暂无', // 设置默认值
      };
      
      const response = await createTask(taskData);
      
      if (response.code === 200) {
        message.success('创建任务成功');
        setNewTaskModalVisible(false);
        createTaskForm.resetFields();
        fetchTasks();
      } else {
        message.error('创建任务失败');
      }
    } catch (error) {
      console.error('创建任务失败:', error);
    }
  };

  // 打开新建任务弹窗
  const showNewTaskModal = () => {
    setNewTaskModalVisible(true); // 打开弹窗
    createTaskForm.resetFields(); // 重置表单
    fetchUserNames(); // 获取用户列表
  };

  // 重置搜索条件并刷新任务列表
  const handleReset = () => {
    form.resetFields();
    fetchTasks();
    message.success('已重置搜索条件');
  };

  // 处理打开任务详情
  const handleOpenTaskDetail = (task: Task) => {
    setSelectedTask(task);
    setTaskDetailVisible(true);
  };

  // 处理关闭任务详情
  const handleCloseTaskDetail = () => {
    setTaskDetailVisible(false);
  };

  // 处理编辑任务
  const handleEditTask = () => {
    if (selectedTask && selectedTask.status === 'inProgress') {
      // 如果是进行中状态的任务，设置标记
      setIsInProgressEdit(true);
    } else {
      setIsInProgressEdit(false);
    }
    setTaskDetailVisible(false); // 关闭详情弹窗
    setTaskEditVisible(true); // 打开编辑弹窗
  };

  // 处理关闭编辑任务
  const handleCloseEditTask = () => {
    setTaskEditVisible(false);
    // 如果是从进行中详情弹窗点击编辑按钮打开的编辑弹窗，关闭时不需要再显示详情弹窗
    setIsInProgressEdit(false);
  };

  // 处理编辑成功
  const handleEditSuccess = () => {
    setTaskEditVisible(false);
    setIsInProgressEdit(false);
    message.success('任务更新成功！');
    fetchTasks();
  };

  // 打开创建任务弹窗
  const handleOpenCreateTask = () => {
    setCreateTaskVisible(true);
  };

  // 关闭创建任务弹窗
  const handleCloseCreateTask = () => {
    setCreateTaskVisible(false);
  };

  // 创建任务成功
  const handleCreateSuccess = () => {
    setCreateTaskVisible(false);
    message.success('任务创建成功！');
    fetchTasks();
  };

  // 处理滚动到指定任务
  const scrollToTask = (taskId: string | number) => {
    console.log('【任务定位】开始执行scrollToTask函数, 目标任务ID:', taskId);
    
    // 首先查找任务在哪个列中
    let targetTask: Task | undefined = undefined;
    let targetColumnId: string | undefined = undefined;
    let targetTaskIndex: number = -1;
    
    // 遍历所有列，查找目标任务
    columns.forEach(column => {
      const taskIndex = column.tasks.findIndex(task => String(task.id) === String(taskId));
      if (taskIndex >= 0) {
        targetTask = column.tasks[taskIndex];
        targetColumnId = column.id;
        targetTaskIndex = taskIndex;
        console.log('【任务定位】找到目标任务, 所在列:', column.title, ', 当前位置索引:', taskIndex);
      }
    });
    
    if (!targetTask || !targetColumnId) {
      console.warn('【任务定位】未找到目标任务, ID:', taskId);
      return;
    }
    
    // 创建新的列数据，将目标任务移到列顶部
    const newColumns = [...columns];
    const columnIndex = newColumns.findIndex(col => col.id === targetColumnId);
    
    if (columnIndex >= 0 && targetTaskIndex > 0) {
      // 制作新的任务数组，将目标任务移到最前面
      const columnTasks = [...newColumns[columnIndex].tasks];
      const taskToMove = columnTasks[targetTaskIndex];
      
      // 从当前位置删除任务
      columnTasks.splice(targetTaskIndex, 1);
      // 插入到最前面
      columnTasks.unshift(taskToMove);
      
      // 更新列数据
      newColumns[columnIndex] = {
        ...newColumns[columnIndex],
        tasks: columnTasks
      };
      
      console.log('【任务定位】任务已移动到列顶部');
      
      // 更新状态
      setColumns(newColumns);
    } else {
      console.log('【任务定位】任务已在列顶部，无需移动');
    }
    
    // 延迟执行滚动操作，确保DOM已更新
    setTimeout(() => {
      const taskElement = document.getElementById(`task-${taskId}`);
      if (taskElement) {
        console.log('【任务定位】找到任务元素，准备滚动');
        // 找到任务所在的列容器
        const columnElement = taskElement.closest('.task-column');
        if (columnElement) {
          // 计算滚动位置，使任务卡片居中显示
          const taskRect = taskElement.getBoundingClientRect();
          const columnRect = columnElement.getBoundingClientRect();
          
          const scrollTop = taskElement.offsetTop - columnRect.height / 2 + taskRect.height / 2;
          
          console.log('【任务定位】执行滚动，滚动位置:', scrollTop);
          // 平滑滚动到任务位置
          columnElement.scrollTo({
            top: scrollTop,
            behavior: 'smooth'
          });
        } else {
          console.warn('【任务定位】未找到列容器元素');
        }
      } else {
        console.warn('【任务定位】未找到任务元素, ID:', `task-${taskId}`);
      }
    }, 100);
  };

  return (
    <PageContainer loading={loading}>
      <div className="flex flex-col mb-4">
        <Alert
          message="任务看板使用说明"
          description={
            <Paragraph className="mb-0">
              通过拖拽可以改变任务状态。当任务拖到"已完成"列时，系统将自动记录完成时间。
            </Paragraph>
          }
          type="info"
          showIcon
          icon={<InfoCircleOutlined />}
          className="mb-4"
        />
      </div>

      {/* 搜索区域 */}
      <Card className="mb-6">
        <Form form={form} layout="horizontal" onFinish={handleSearch}>
          <Row gutter={[16, 16]}>
            <Col xs={24} md={4}>
              <Form.Item name="title" className="mb-0">
                <Input placeholder="任务标题" prefix={<SearchOutlined />} allowClear />
              </Form.Item>
            </Col>
            <Col xs={24} md={4}>
              <Form.Item name="creater" className="mb-0">
                <Input placeholder="创建人" prefix={<UserOutlined />} allowClear />
              </Form.Item>
            </Col>
            <Col xs={24} md={4}>
              <Form.Item name="receiver" className="mb-0">
                <Input placeholder="处理人" prefix={<UserOutlined />} allowClear />
              </Form.Item>
            </Col>
            <Col xs={24} md={4}>
              <Form.Item name="type" className="mb-0">
                <Select placeholder="需求类型" allowClear onChange={handleTypeChange} style={{ width: '100%' }}>
                  {taskTypes.map(type => (
                    <Option key={type} value={type}>{type}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} md={4}>
              <Form.Item name="subTypes" className="mb-0">
                <Select 
                  placeholder="子类型" 
                  allowClear 
                  mode="multiple"
                  options={getSubTypesByType(selectedType).map(subType => ({
                    label: subType,
                    value: subType
                  }))}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col xs={24} md={4}>
              <Space>
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  onClick={handleSearch}
                >
                  搜索
                </Button>
                <Button
                  icon={<PlusOutlined />}
                  onClick={handleOpenCreateTask}
                >
                  新建任务
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={handleReset}
                >
                  重置
                </Button>
                <Button
                  icon={<UserOutlined />}
                  onClick={fetchMyTasks}
                >
                  我的
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 任务看板 */}
      <DragDropContext onDragEnd={handleDragEnd}>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {columns.map(column => (
            <TaskColumn 
              key={column.id} 
              column={column} 
              onEditTask={(task) => {
                setSelectedTask(task);
                setIsInProgressEdit(task.status === 'inProgress');
                setTaskEditVisible(true);
              }} 
              scrollToTask={scrollToTask}
            />
          ))}
        </div>
      </DragDropContext>

      {/* 任务详情弹窗 */}
      {selectedTask && (
        <TaskDetailModal
          visible={taskDetailVisible}
          task={selectedTask}
          onCancel={handleCloseTaskDetail}
          onEdit={handleEditTask}
          showEditButton={true}
        />
      )}

      {/* 任务编辑弹窗 */}
      {selectedTask && (
        <TaskEditModal
          visible={taskEditVisible}
          task={selectedTask}
          onCancel={handleCloseEditTask}
          onSuccess={handleEditSuccess}
          // 进行中任务特殊处理
          disableTitle={isInProgressEdit || false}
          requiredFields={isInProgressEdit ? [] : []}
          // 进行中任务限制编辑字段
          hiddenFields={isInProgressEdit ? [] : []}
          // 进行中任务允许编辑这几个字段
          disableAllExcept={isInProgressEdit ? ['thisWeekPlan', 'nextWeekPlan', 'problems', 'process'] : []}
        />
      )}

      {/* 创建任务弹窗 */}
      <CreateTaskModal
        visible={createTaskVisible}
        onCancel={handleCloseCreateTask}
        onSuccess={handleCreateSuccess}
        username={username}
        parentId={undefined}
      />

      {/* 拖拽任务编辑弹窗 */}
      {draggedTask && (
        <TaskEditModal
          visible={editModalVisible}
          task={draggedTask}
          onCancel={handleEditCancel}
          onSuccess={() => {
            setEditModalVisible(false);
            setDraggedTask(null);
            message.success('任务更新成功！');
            fetchTasks();
          }}
          disableTitle={true}
          requiredFields={['type', 'subType', 'level', 'receiver']}
          forceStatus={'inProgress' as TaskStatus}
          hiddenFields={['thisWeekPlan', 'nextWeekPlan', 'problems']}
        />
      )}
    </PageContainer>
  );
};

export default TaskBoard; 